package com.topnav.mc.admin.security.filter;

import com.topnav.mc.admin.security.config.JwtProperties;
import com.topnav.mc.admin.security.filter.manager.CustomAccessDecisionManager;
import com.topnav.mc.admin.security.filter.service.CustomFilterInvocationSecurityMetadataSource;
import com.topnav.mc.admin.security.jwt.utils.JwtTokenUtil;
import com.topnav.mc.common.Constant;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import java.io.IOException;

/**
 * 说明：自定义拦截器
 * @类名: CutomFilterSecurityInterceptor
 * <p>
 * 单独定一个继承自 HandlerInterceptorAdapter 的拦截器，用WebMvcConfigurationSupport 加入
 * 与Spring security 有冲突（可以启动，但如访问swagger的 doc.html 都被拦截了）
 * 暂时不明白原因
 * </p>
 * @author   kenny
 * @Date	 2022年2月10日下午5:12:29
 */
@Service
public class CutomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
	@Resource
	private JwtProperties jwtProperties;

    @Autowired
    private CustomFilterInvocationSecurityMetadataSource securityMetadataSource;

	private MDC.MDCCloseable mdcClose;

	public void invoke(FilterInvocation fi) throws IOException, ServletException {
		//fi里面有一个被拦截的url
		//里面调用CustomFilterInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
		//再调用CustomAccessDecisionManager的decide方法来校验用户的权限是否足够
		InterceptorStatusToken token = super.beforeInvocation(fi);
		try {
			/**
			 * 把token 存入 MDC，使用时先从MDC取出，再由缓存取用户单位的权限*
			 * 在程序其它地方都可以取出 token
			 */
			String tokenStr = fi.getRequest().getHeader(jwtProperties.getHeader());
			if (StringUtils.isEmpty(tokenStr)){
				tokenStr = fi.getRequest().getParameter(jwtProperties.getHeader());
			}

			if (!StringUtils.isEmpty(tokenStr))
				//存入MDC 结束后移除
				mdcClose = MDC.putCloseable(Constant.MDC_TOEKN, tokenStr);

			//执行下一个拦截器
		    fi.getChain().doFilter(fi.getRequest(), fi.getResponse());

			//return true;
		} finally {
		    this.afterInvocation(token, null);
		}
	}
	@Override
	protected Object afterInvocation(InterceptorStatusToken token, Object returnedObject) {
		//从MDC移除traceCode
		if (mdcClose != null){
			mdcClose.close();
		}
		return super.afterInvocation(token,returnedObject);
	}

    @Autowired
    public void setCutomFilterSecurityInterceptor(CustomAccessDecisionManager customAccessDecisionManager) {
        super.setAccessDecisionManager(customAccessDecisionManager);
    }

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		FilterInvocation fi = new FilterInvocation(request, response, chain);
        invoke(fi);
	}

	@Override
	public Class<?> getSecureObjectClass() {
		return FilterInvocation.class;
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

}
